package simple;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class SocketClient {
    public static void main(String[] args) {
        // 服务器地址和端口
        String serverAddress = args[0];
        int serverPort = Integer.parseInt(args[1]);
        String message = "Hello, Server!"; // 要发送的消息

        try {
            // 创建Socket连接
            Socket socket = new Socket(serverAddress, serverPort);
            System.out.println("Connected to the server.");

            // 获取输出流，用于发送数据
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            out.println(message); // 发送消息
            System.out.println("Message sent: " + message);

            // 可以选择接收服务器的响应（如果服务器有返回数据）
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String response = in.readLine(); // 读取服务器返回的消息
            if (response != null) {
                System.out.println("Server response: " + response);
            }

            // 关闭资源
            out.close();
            in.close();
            socket.close();
        } catch (Exception e) {
            e.printStackTrace(); // 打印异常信息
        }
    }
}